<template>
	<view class="container">
		<uni-forms ref="loginForm" :rules="rules" :modelValue="formData" label-position="top">
			<uni-forms-item label="用户名" required name="username">
				<uni-easyinput v-model="formData.username" placeholder="请输入用户名" />
			</uni-forms-item>
			<uni-forms-item label="密码" required name="password">
				<uni-easyinput type="password" v-model="formData.password" placeholder="请输入密码" />
			</uni-forms-item>
		</uni-forms>
		<button type="primary" @click="submit()">登录</button>
	</view>
</template>

<script>
	import {login} from '@/api/login.js'
	import {setUid,getUid,setUsername,getUesrname, getUsername} from '@/utils/userInfo'
	
	export default{
		data(){
			return {
				// 基础表单数据
				formData: {
					username: '',
					password: ''
				},
				// 校验规则
				rules: {
					username: {
						rules: [{
							required: true,
							errorMessage: '用户名不能为空'
						}]
					},
					password: {
						rules: [{
							required: true,
							errorMessage: '密码不能为空'
						},{
							minLength: 5,
							maxLength: 16,
							errorMessage: '{label}长度在 {minLength} 到 {maxLength} 个字符',
						}]
					}
				},
			}
		},
		onLoad() {
			/*
			 history路由刷新报404错误
			 在服务器端做处理：报404就跳转到登录页
			 在登录页中做判断，如果有用户id，就表示登录成功，跳转到首页
			 */
			const uid = getUid()
			if(uid !== "" ){
				uni.setStorageSync('index_ajax_type', "init")
				uni.redirectTo({
					url:'./note/index'
				})
			}
		},
		methods:{
			submit(ref) {
				// console.log(this.baseFormData);
				this.$refs['loginForm'].validate().then(res => {
					// console.log('success', res);
					
					login(res).then( res => {
						// console.log("login.js  sucess:",res)
						setUid( res.data.id)
						// console.log("uid:",getUid())
						setUsername(res.data.username)
						// console.log("username:",getUsername())
						uni.setStorageSync('index_ajax_type', "init")
						uni.redirectTo({
							url:'./note/index'
						})
						
					})
				}).catch(err => {
					console.log('err', err);
				})
			},
		}
	}
</script>

<style>
	.container {
		padding: 15px;
		background-color: #fff;
	}
</style>